import { useEffect, useState, useRef, useMemo, createElement } from "react";
import type { DataNode } from 'antd/es/tree';
import { RespSysDataType, getDeptTree } from "../../api";

export const useTreeData = () => {
  const [loading, setLoading] = useState(false);
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const dataListRef = useRef<{ key: React.Key; title: string }[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [searchValue, setSearchValue] = useState("");
  const realTreeData = useMemo(() => filterTree(treeData, searchValue), [searchValue, treeData])

  useEffect(() => {
    fetchDeptTree();
  }, []);

  useEffect(() => {
    onSearch("")
  }, [treeData])

  /**
   * 获取组织树
   */
  const fetchDeptTree = () => {
    setLoading(true);
    getDeptTree().then((resp) => {
      setTreeData(formatDeptTree(resp.data.deps, dataListRef.current));
      setLoading(false);
    });
  }

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  /**
   * 监听搜索
   */
  const onSearch = (value: string) => {
    const newExpandedKeys = dataListRef.current
      .map((item) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, treeData);
        }
        return null;
      })
      .filter((item, i, self): item is React.Key => !!(item && self.indexOf(item) === i));

    // console.log("newExpandedKeys->", newExpandedKeys);
    setSearchValue(value);
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(true);
  };

  return { loading, treeData:realTreeData, expandedKeys, autoExpandParent, onExpand, onSearch };
}

/**
 * 格式化组织树
 */
const formatDeptTree = (data: RespSysDataType.DeptTreeItem[], dataList: { key: React.Key; title: string }[]): DataNode[] => {
  return data.map(item => {
    dataList.push({ key: item.deptId, title: item.deptName });
    return ({
      key: item.deptId,
      title: item.deptName,
      children: item.children ? formatDeptTree(item.children, dataList) : []
    })
  })
}

/**
 * 获取父级key
 */
const getParentKey = (key: React.Key, tree: DataNode[]): React.Key => {
  let parentKey: React.Key;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey!;
};

/**
 * 过滤树
 */
const filterTree = (data: DataNode[], searchValue: string): DataNode[] => data.map((item) => {
  const strTitle = item.title as string;
  const index = strTitle.indexOf(searchValue);
  const beforeStr = strTitle.substring(0, index);
  const afterStr = strTitle.slice(index + searchValue.length);
  const title = index > -1 ? createElement("span", {
    children: [
      createElement("span", {children: beforeStr, key: 0}), 
      createElement("span", {children: searchValue, key: 1, style: {color: "#49c449"}}), 
      createElement("span", {children: afterStr, key: 2}), 
    ]
  }): createElement("span", {children: strTitle});
  
  if (item.children) {
    return { title, key: item.key, children: filterTree(item.children, searchValue) };
  }

  return {
    title,
    key: item.key,
  };
});
